﻿namespace DependencyPropertyChangedSample.ComponentModel
{
    using System;
    using System.Windows;
    using System.Windows.Data;

    public static class DependencyPropertyChangedHandlerAttacher
    {
        /// <summary>
        /// Registers a DependencyPropertyChangedEvent to a DependencyProperty. 
        /// </summary>
        /// <param name="target">Target object that holds the DependencyProperty.</param>
        /// <param name="propertyPath">Path of the property.</param>
        /// <param name="dependencyPropertyChanged">Handler to register</param>
        public static void Register(DependencyObject target, string propertyPath, DependencyPropertyChangedEventHandler dependencyPropertyChanged)
        {
            Binding binding = new Binding(propertyPath) { Source = target };

            var property = DependencyProperty.RegisterAttached("_" + Guid.NewGuid().ToString("N"), typeof(object), typeof(System.Windows.Controls.UserControl),
                new PropertyMetadata((o, e) =>
                {
                    o.Dispatcher.BeginInvoke(() => dependencyPropertyChanged.Invoke(o, e));
                })
            );

            BindingOperations.SetBinding(target, property, binding);
        }
    }
}
